from langchain_openai import ChatOpenAI
from langchain.schema import HumanMessage, SystemMessage
import os
import json

class Agent:

    def __init__(self):

        self.api_dict = self.load_api_dict()

        self.chat_model = ChatOpenAI(
            temperature=self.api_dict['chat']['temperature'],
            model=self.api_dict['chat']['model'],
            openai_api_key=self.api_dict['chat']['openai_api_key'],
            openai_api_base=self.api_dict['chat']['openai_api_base'],
        )

    def load_api_dict(self, filepath='data/api_dict.json'):

        if os.path.exists(filepath):
            try:
                with open(filepath, 'r', encoding='utf-8') as f:
                    loaded_dict = json.load(f)
                    if isinstance(loaded_dict, dict):
                        return loaded_dict
            except (json.JSONDecodeError, FileNotFoundError, PermissionError) as e:
                print(f"加载api_dict时出错: {str(e)}")
        else:
            print("api_dict不存在")

    def save_api_dict(self, filepath='data/api_dict.json'):
        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(self.api_dict, f, ensure_ascii=False, indent=4)
            return True
        except (FileNotFoundError, PermissionError) as e:
            print(f"保存api_dict时出错: {str(e)}")
            return False

if __name__ == '__main__':

    api_dict = {
        'chat': {
            'openai_api_base': 'https://open.bigmodel.cn/api/paas/v4/',
            'openai_api_key': 'fc842bc2b818449cac57093f0e20113d.fadP35HLfM0caKOl',
            'model': 'glm-4.5',
        }
    }
    
    robot = Agent(api_dict)
    
    messages = [
        SystemMessage(content="你是一名军事参谋，能够帮助指挥员在兵棋推演中进行裁决。你可以根据用户提供的裁决表数据，结合当前的战场态势，给出合理的裁决建议。"),
        HumanMessage(content="你能做什么？")
    ]

    print('thinking...')

    try:
        output = robot.chat_model.invoke(messages).content
    except:
        output = 'error: 智能体配置错误'
    print(output)